package bootstrap

import (
	"fmt"
	"log"
	"math"
	"sort"
	"time"
	"math/rand"
	"github.com/869413421/wechatbot/globalmap"
	"github.com/869413421/wechatbot/handlers"
	"github.com/eatmoreapple/openwechat"
	"github.com/robfig/cron/v3"
)

func Run() {

	//bot := openwechat.DefaultBot()
	bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式，上面登录不上的可以尝试切换这种模式

	// 注册消息处理函数
	bot.MessageHandler = handlers.Handler
	// 注册登陆二维码回调
	bot.UUIDCallback = openwechat.PrintlnQrcodeUrl

	// 创建热存储容器对象
	reloadStorage := openwechat.NewJsonFileHotReloadStorage("storage.json")
	// 执行热登录
	err := bot.HotLogin(reloadStorage)
	if err != nil {
		if err = bot.Login(); err != nil {
			log.Printf("login error: %v \n", err)
			return
		}
	}
	self, err := bot.GetCurrentUser()
	fmt.Println("self", self)
	if err != nil {
		fmt.Println(err)
		return
	}
	startToSendMessage(self)

	crontab(self)
	crontab2(self)
	crontab3(self)
	crontab4(self)
	clearLimitLock()
	crontab5(self)
	// crontabGroup1ForDay(self)
	// 阻塞主goroutine, 直到发生异常或者用户主动退出
	bot.Block()
}

func startToSendMessage(self *openwechat.Self) {
	groups, err := self.Groups()
	if err != nil {
		fmt.Println(err)
		return
	}
	self.SendTextToGroup(groups.GetByNickName("私斋蒸鹅心"), "锵锵~上班咯！")
}

func countData2() string {
	result := "@所有人 每日记录"
	for key, value := range dateMap {
		days := covertDays(value)
		result += "\n" + key + ":" + fmt.Sprint(days)
	}

	return result
}

func covertDays(targetDate string) int {
	layout := "2006/01/02"
	target, _ := time.Parse(layout, targetDate)
	today := time.Now()

	diff := target.Sub(today)
	days := int(diff.Hours() / 24)

	return int(math.Abs(float64(days)))
}

func crontab(self *openwechat.Self) {
	spec := "0 0 10,11,12,13,14,15,16,17,18 * * 1,2,3,4,5 "
	c := cron.New(cron.WithSeconds())
	c.AddFunc(spec, func() {
		sendMsg(self)
	})
	// sendMsg(self)
	c.Start()

}

func crontab2(self *openwechat.Self) {
	spec := "8 26 10 * * ?"
	c := cron.New(cron.WithSeconds())
	c.AddFunc(spec, func() {
		sendMsg2(self)
	})
	// sendMsg2(self)
	c.Start()
}

func crontab3(self *openwechat.Self) {
	spec := "0 30 11 * * ?"
	c := cron.New(cron.WithSeconds())
	c.AddFunc(spec, func() {
		rand.Seed(time.Now().UnixNano())
		randomIndex := rand.Intn(len(spells))
		randomSpell := spells[randomIndex]
		sendMsg3(self, randomSpell, "私斋蒸鹅心")
	})
	// sendMsg2(self)
	c.Start()
}


// func crontab3(self *openwechat.Self) {
// 	// spec := "0 0 18 * * 1,2,3,4,5"
// 	spec := "0 0 10,11,12,13,14,15,16,17,18 * * 1,2,3,4,5 "
// 	c := cron.New(cron.WithSeconds())
// 	c.AddFunc(spec, func() {
// 		sendMsg3(self)
// 	})
// 	c.Start()
// }

func crontab4(self *openwechat.Self) {
	spec := "0 0 18 * * 1,2,3,4,5"
	c := cron.New(cron.WithSeconds())
	c.AddFunc(spec, func() {
		sendMsg4(self)
	})
	c.Start()
}
func crontab5(self *openwechat.Self) {
	spec := "0 28 10 * * 5"
	c := cron.New(cron.WithSeconds())
	c.AddFunc(spec, func() {
		sendMsg5(self)
	})
	c.Start()
}

func clearLimitLock() {
	spec := "0 * * * * *"
	c := cron.New(cron.WithSeconds())
	c.AddFunc(spec, func() {
		globalmap.LimitLock = make(map[string]int)
	})
	c.Start()
}

func sendMsg2(self *openwechat.Self) {
	groups, err := self.Groups()
	if err != nil {
		fmt.Println(err)
		return
	}
	self.SendTextToGroup(groups.GetByNickName("私斋蒸鹅心"), countData2())
}

func sendMsg3(self *openwechat.Self, msg string, groupName string) {
	groups, err := self.Groups()
	if err != nil {
		fmt.Println(err)
		return
	}
	self.SendTextToGroup(groups.GetByNickName(groupName), msg)
}

// func sendMsg3(self *openwechat.Self) {
// 	groups, err := self.Groups()
// 	if err != nil {
// 		fmt.Println(err)
// 		return
// 	}
// 	self.SendTextToGroup(groups.GetByNickName("🀄兩吋的好朋友"), countData3())
// }

func sendMsg4(self *openwechat.Self) {
	groups, err := self.Groups()
	if err != nil {
		fmt.Println(err)
		return
	}
	self.SendTextToGroup(groups.GetByNickName("私斋蒸鹅心"), countData4())
}

func sendMsg5(self *openwechat.Self) {
	groups, err := self.Groups()
	if err != nil {
		fmt.Println(err)
		return
	}
	self.SendTextToGroup(groups.GetByNickName("私斋蒸鹅心"), countData5())
}

var dateMap = map[string]string{"小巴的纪念日": "2020/08/26"}
var spells = []string{
	"遮蔽光明的漆黑啊，懷抱黑夜的爆炎啊，吾以紅魔之名，宣言原初之崩壞，在終末王國之地，隱藏力量根源之人，於吾眼前集結吧。Explosion!",
	"向那比黑更黑比暗更暗的深淵，祈求吾之深紅閃光，覺醒之時已然降至，墮入無謬境界的真理啊，化作無窮的扭曲限界吧！起舞吧，起舞吧，起舞吧！吾之魔力奔流所求之物即崩壞，無人能及之崩壞，森羅萬象皆歸塵土，從深淵降臨吧，這是人類最大的攻擊手段，這正是最強的攻擊魔法。Explosion!",
	"暗紅黑炎，萬界之王，縱覽天地之道法，唯吾萬勝之常理，崩壞破壞之異名，永劫之鐵錘於吾前降下。Explosion!在紅蓮之中，燃燒殆盡吧！",
	"吾名大企鹅，乃至高全能的支配者，受命於天之力之人，到來吧，到來吧，火焰的軍勢，回應吾之所求，顯現你的力量吧！Explosion!",
	"遮蔽光明的漆黑啊，懷抱黑夜的爆炎啊，其他暫且不論，在爆裂魔法領域，我誰都不想輸！我的究極破壞魔法！Explosion!",
	"吾之渾身一擊，盲目如同胞之愛，將蘇生變為往生，展現強大的波動，悲哀的禽獸啊，與黑之紅炎共鳴，化為血潮償還罪孽吧！貫穿吧！Explosion!",
	"環繞於吾身的戒律之爐內，深淵之血肉爭鳴咆哮，此刻，融於真紅波動之中吧！貫穿天地吧，Explosion!",
}

func sendMsg(self *openwechat.Self) {
	groups, err := self.Groups()
	if err != nil {
		fmt.Println(err)
		return
	}
	self.SendTextToGroup(groups.GetByNickName("私斋蒸鹅心"), countData())
}

func countData() string {
	currentTime := time.Now()
	formattedTime := currentTime.Format("2006-01-02 15:04:05")
	fmt.Println("Formatted Time:", formattedTime)
	result := ""
	// var values []int
	// for _, v := range globalmap {
	// values = append(values, v)
	// }
	// 对切片进行排序
	// sort.Ints(values)
	var startTime = currentTime.Add(-1 * time.Hour)
	startFormattedTime := startTime.Format("2006-01-02 15:04:05")
	type userKPI struct {
		key   string
		value int
	}
	var lstUserKPI []userKPI
	for k, v := range globalmap.GlobalMap {
		lstUserKPI = append(lstUserKPI, userKPI{k, v})
	}
	if len(lstUserKPI) == 0 {
		return result
	}
	sort.Slice(lstUserKPI, func(i, j int) bool {
		return lstUserKPI[i].value > lstUserKPI[j].value // 降序
	})

	for i := 0; i < len(lstUserKPI); i++ {
		// days := covertDays(value)
		fmt.Println("result:", result)
		var topThreeIcon = ""
		switch i {
		case 0:
			topThreeIcon = "🥇"
		case 1:
			topThreeIcon = "🥈"
		case 2:
			topThreeIcon = "🥉"
		default:
			topThreeIcon = "用户："
		}
		result = result + "\n" + topThreeIcon + fmt.Sprint(lstUserKPI[i].key) + "\n 时间：" + startFormattedTime + " - " + formattedTime + "\n 摸鱼绩效汇总发言:" + fmt.Sprint(lstUserKPI[i].value) + "次\n"
	}
	for _, value := range globalmap.DisableMemberNickNameArr {
		result = result + "\n🤡：" + value + "\n"
	}
	globalmap.GlobalMap = make(map[string]int)

	return result
}

func countData3() string {
	currentTime := time.Now()
	formattedTime := currentTime.Format("2006-01-02 15:04:05")
	fmt.Println("Formatted Time:", formattedTime)
	result := ""
	// var values []int
	// for _, v := range globalmap {
	// values = append(values, v)
	// }
	// 对切片进行排序
	// sort.Ints(values)
	var startTime = currentTime.Add(-1 * time.Hour)
	startFormattedTime := startTime.Format("2006-01-02 15:04:05")
	type userKPI struct {
		key   string
		value int
	}
	var lstUserKPI []userKPI
	for k, v := range globalmap.Group1SpeakCountMap {
		lstUserKPI = append(lstUserKPI, userKPI{k, v})
	}
	if len(lstUserKPI) == 0 {
		return result
	}
	sort.Slice(lstUserKPI, func(i, j int) bool {
		return lstUserKPI[i].value > lstUserKPI[j].value // 降序
	})

	for _, user := range lstUserKPI {
		// days := covertDays(value)
		fmt.Println("result:", result)
		result = result + "\n 用户：" + fmt.Sprint(user.key) + "\n 时间：" + startFormattedTime + " - " + formattedTime + "\n 摸鱼绩效汇总发言:" + fmt.Sprint(user.value) + "次\n"
	}
	globalmap.Group1SpeakCountMap = make(map[string]int)

	return result
}

func countData4() string {
	currentTime := time.Now()
	formattedTime := currentTime.Format("2006-01-02 15:04:05")
	fmt.Println("Formatted Time:", formattedTime)
	result := ""
	// var values []int
	// for _, v := range globalmap {
	// values = append(values, v)
	// }
	// 对切片进行排序
	// sort.Ints(values)
	var startTime = currentTime.Add(-9 * time.Hour)
	startFormattedTime := startTime.Format("2006-01-02 15:04:05")
	type userKPI struct {
		key   string
		value int
	}
	var lstUserKPI []userKPI
	for k, v := range globalmap.Group2SpeakCountMap {
		lstUserKPI = append(lstUserKPI, userKPI{k, v})
	}
	if len(lstUserKPI) == 0 {
		return result
	}
	sort.Slice(lstUserKPI, func(i, j int) bool {
		return lstUserKPI[i].value > lstUserKPI[j].value // 降序
	})

	for i := 0; i < len(lstUserKPI); i++ {
		// days := covertDays(value)
		fmt.Println("result:", result)
		var topThreeIcon = ""
		switch i {
		case 0:
			topThreeIcon = "🥇"
		case 1:
			topThreeIcon = "🥈"
		case 2:
			topThreeIcon = "🥉"
		default:
			topThreeIcon = "用户："
		}
		result = result + "\n" + topThreeIcon + fmt.Sprint(lstUserKPI[i].key) + "\n 时间：" + startFormattedTime + " - " + formattedTime + "\n 摸鱼绩效汇总发言:" + fmt.Sprint(lstUserKPI[i].value) + "次\n"
	}
	for _, value := range globalmap.DisableMemberNickNameArr {
		result = result + "\n🤡：" + value + "\n"
	}

	// for _, user := range lstUserKPI {
	// 	// days := covertDays(value)
	// 	fmt.Println("result:", result)
	// 	switch
	// 	result = result + "\n 用户：" + fmt.Sprint(user.key) + "\n 时间：" + startFormattedTime + " - " + formattedTime + "\n 摸鱼绩效汇总发言:" + fmt.Sprint(user.value) + "次\n"
	// }
	globalmap.Group2SpeakCountMap = make(map[string]int)

	return result
}

func countData5() string {
	currentTime := time.Now()
	formattedTime := currentTime.Format("2006-01-02 15:04:05")
	fmt.Println("Formatted Time:", formattedTime)
	result := "周五建行生活10:30活动即将开始！！现在时间：" + formattedTime
	return result
}
